<template>
  <div class="container">
    <template>
      <div v-if="mode === 'edit'">
        <el-upload
          action=""
          :auto-upload="false"
          :limit="limitCount"
          accept="image/png,image/jpeg,image/jpg"
          :class="{'hide':hideUpload}"
          :show-file-list="true"
          :file-list="imgFileList"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-change="imgHandleChange"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-dialog
          :visible.sync="dialogVisible"
          size="tiny"
        >
          <img
            width="100%"
            :src="dialogImageUrl"
            alt="预览图片"
          >
        </el-dialog>
        <el-button
          class="recognize-btn"
          type="primary"
          @click="recognizeRequest"
          :disabled="recognizeDisabled"
          :loading="recognizeLoading"
        >
          {{ btnText }}
        </el-button>
      </div>
      <div v-else>{{ value }}</div>
    </template>
  </div>
</template>

<script>
import axios from "axios"
import customRequest from "../../mixins/custom-request.js"
import CryptoJS from "crypto-js"
export default {
  name: "idCard",
  components: {},
  mixins: [customRequest],
  props: {
    value: {},
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    // url: {
    //   type: String,
    //   default: "",
    // },
    // token: {
    //   type: String,
    //   default: "",
    // },
    // paasid: {
    //   type: String,
    //   default: "",
    // },
    // trackId: {
    //   type: String,
    //   default: "",
    // },
  },
  data() {
    return {
      btnText: "身份证识别",
      imgFileList: [],
      hideUpload: false,
      dialogImageUrl: "",
      dialogVisible: false,
      limitCount: 1,
      recognizeLoading: false,
      belong: '身份证识别'
    };
  },

  watch: {},
  mounted() {
    if (this.value) {
      if (this.mode == "view") {
        this.disabled = true;
      }
    }
  },
  computed: {
    imgFileLength() {
      return _.get(this.imgFileList, "length", 0)
    },
    recognizeDisabled() {
      return this.disabled || this.imgFileLength <= 0;
    },
  },
  methods: {
    handleRemove(file, fileList) {
      this.hideUpload = fileList.length >= this.limitCount;
      this.imgFileList = fileList
      this.disabled = false
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    imgHandleChange(file, fileList) {
      this.hideUpload = fileList.length >= this.limitCount;
      this.imgFileList = fileList
    },
    uploadImgToBase64 (file) {
     return new Promise((resolve, reject) => {
       const reader = new FileReader()
       reader.readAsDataURL(file)
       reader.onload = function () {
        resolve(reader)
       }
       reader.onerror = reject
     })
    },
    async recognizeRequest() {
      if (this.imgFileLength <= 0) return
      this.recognizeLoading = true;
      const url = this.getCodeValueByCode('ID_CARD_RECOGNIZE_URL')
      const token = this.getCodeValueByCode('ID_CARD_RECOGNIZE_TOKEN')
      const paasid = this.getCodeValueByCode('ID_CARD_RECOGNIZE_PAASID')
      const trackId = this.getCodeValueByCode('ID_CARD_RECOGNIZE_TRACK_ID')
      const requestUrl = `${this.preurl}api/afc/integration/idCardRecognition`
      const headers = this.header
      const timestamp = (Date.now() / 1000).toFixed();
      const nonce = Math.random().toString(36).substring(2);
      // const { url, token, paasid, trackId } = this;
      const signature = CryptoJS.SHA256(timestamp + token + nonce + timestamp).toString(CryptoJS.enc.Hex).toUpperCase();
      const dataType = "ZERO";
      const template = "id_card";
      const payload = { url, paasid, trackId, timestamp, nonce, signature, dataType, template, imageDataList: [] };
      for (let item of this.imgFileList) {
        const { raw } = item;
        const res = await this.uploadImgToBase64(raw);
        const { result } = res
        const content = result.replace(/.*;base64,/, '')
        payload.imageDataList.push(content)
      }
      axios.post(`${requestUrl}`, payload, { headers }).then((resp) => {
        const { data } = resp
        if (data) {
          this.$message.success("认证成功")
        } else {
          this.$message.error("认证失败")
        }
        this.disabled = true
      }).catch((err) => {
        console.log("请求接口错误:", err)
        const message = _.get(err, "response.data.errorLocalizedMessage")
        this.$message.error(message || err.message)
      }).finally(() => {
        this.recognizeLoading = false;
      })
    },
  },
};
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
}
.recognize-btn {
  margin: 10px 0;
}
.recognize-result {
  text-align: justify;
}
</style>
<style lang="scss">
.hide .el-upload--picture-card {
  display: none;
}
</style>
